<template>
  <div style="display: inline-block;">
    <el-upload
      class="avatar-uploader"
      :action="qiniuUrl"
      :data="postData"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :on-success="handleAvatarSuccess"
      :http-request="qiniuRequest"
      :disabled="imageLoading">
      <div class="upload-box" @click="fileClick()">
        <a href="#" style="color: #409EFF; font-size: 12px;" :loading="imageLoading">上传</a>
      </div>
    </el-upload>
  </div>
</template>

<script>
  import * as qiniuAPI from '@/api/qiniu'
  import lrz from 'lrz'
  export default {
    name: '',
    data() {
      return {
        imageLoading: false,
        name: '',
        postData: {
          token: ''
        },
        currentFile: '',
        imageUrl: '',
        currentFileSize: 0
      }
    },
    props: {
      mainData: {
        type: Object,
        default: function() {
          return {
            name: ''
          }
        }
      },
      listIndex: {
        type: Number,
        default: function() {
          return {
            name: 0
          }
        }
      }
    },
    methods: {
      fileClick() {
        const that = this
        that.currentFile = ''
        qiniuAPI.getToken().then(res => {
          that.postData.token = res.data
          console.info(that.postData.token)
        }).catch(err => {
          console.log(err)
        })
      },
      beforeAvatarUpload(file) {
        // 图片本地预览地址
        this.imageUrl = URL.createObjectURL(file)
        // 当前选中文件对象
        this.currentFile = file
        // 当前文件大小， 因为后面要压缩，这里设置为0即可， 压缩后补加进来
        this.currentFileSize = 0
        // 验证图片的大小的格式是否合法
        const a = this.tools.authImage(file)
        this.imageLoading = true
        if (!a) {
          this.imageLoading = false
        }
        return a
      },
      handleAvatarSuccess(key) {
        // 上传成功
        this.$emit('imageUploadSuccess', key, this.mainData, this.listIndex)
      },
      qiniuRequest(req) {
        const that = this
        const file = req.file
        console.log('压缩前图片大小', file.size)
        lrz(file, { quality: 0.6 }).then(res => {
          const config = {
            headers: { 'Content-Type': 'multipart/form-data' }
          }
          // 将图片的大小改为压缩后的的小
          that.currentFileSize = res.file.size
          console.log('压缩后图片大小', res.file.size)
          const formData = new FormData()
          formData.append('file', res.file)
          formData.append('token', that.postData.token)
          that.$http.post(that.qiniuUrl, formData, config).then(respone => {
            //  respone.data.key
            console.info(respone.data.key)
            this.handleAvatarSuccess(respone.data.key)
          })
        })
      }
    }
  }
</script>

<style scoped>

</style>
